<template>
	<sc-dialog
		v-model="visible"
		show-fullscreen
		class="column-dialog"
		:title="titleMap[mode]"
		width="900px"
		destroy-on-close
		@close="close"
	>
		<el-form
			ref="formRef"
			label-width="100px"
			:model="formData"
			:rules="rules"
		>
			<el-tabs
				class="tabs-pages"
				v-model="tabs.value"
				:before-leave="beforeLeave"
				stretch
				@tab-click="tabsClick"
			>
				<el-tab-pane label="基础设置" name="0" lazy>
					<el-row>
						<el-col :span="12">
							<el-form-item label="活动名称" prop="name">
								<el-input
									v-model="formData.name"
									placeholder="请输入活动名称"
									:maxlength="50"
									show-word-limit
									clearable
									:style="{ width: '100%' }"
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="状态" prop="status" required>
								<el-switch
									v-model="formData.status"
								></el-switch>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="副名称" prop="subName">
						<el-input
							v-model="formData.subName"
							placeholder="请输入活动副名称(选填)"
							:maxlength="50"
							show-word-limit
							clearable
							:style="{ width: '100%' }"
						></el-input>
					</el-form-item>
					<el-form-item label="活动日期">
						<el-col :span="11">
							<el-date-picker
								v-model="formData.startTime"
								type="datetime"
								placeholder="活动开始时间"
								style="width: 100%"
							/>
						</el-col>
						<el-col :span="2" class="text-center">
							<span class="text-gray-500">-</span>
						</el-col>
						<el-col :span="11">
							<el-date-picker
								v-model="formData.endTime"
								type="datetime"
								placeholder="活动结束时间"
								style="width: 100%"
							/>
						</el-col>
					</el-form-item>

					<el-form-item label="活动规则" class="edior">
						<sc-editor
							v-model="formData.summary"
							placeholder="请输入"
							:height="200"
						></sc-editor>
					</el-form-item>
				</el-tab-pane>
				<el-tab-pane label="奖品设置" name="1" lazy>
					<el-form-item label="奖品">
						<sc-form-table
							v-model="formData.prizes"
							:addTemplate="addTemplate"
							drag-sort
							placeholder="暂无数据"
						>
							<el-table-column
								prop="name"
								label="奖品名称"
								width="120"
							>
								<template #default="scope">
									<el-input
										v-model="scope.row.name"
										placeholder="请输入内容"
									></el-input>
								</template>
							</el-table-column>
							<el-table-column
								prop="ratio"
								label="获奖概率"
								width="120"
							>
								<template #default="scope">
									<el-input
										class="ratio"
										v-model="scope.row.ratio"
										placeholder="请输入获奖概率"
										><template #append>%</template>
									</el-input>
								</template>
							</el-table-column>
							<el-table-column
								prop="code"
								label="奖品值"
								width="180"
							>
								<template #default="scope">
									<el-input
										v-model="scope.row.code"
										placeholder="请输入内容"
									></el-input>
								</template>
							</el-table-column>
							<el-table-column
								prop="user"
								label="奖品内定"
								width="160"
							>
								<template #default="scope">
									<el-button
										type="primary"
										:disabled="formData.id == 0"
										size="small"
										@click="selectUser(scope.row)"
										>选择会员</el-button
									>
									<el-button
										type="success"
										:disabled="formData.id == 0"
										size="small"
										@click="lookUser(scope.row)"
										>查看</el-button
									>
								</template>
							</el-table-column>
						</sc-form-table>
						<el-alert
							class="cur-alert"
							show-icon
							title="请将概率合计设置为100%"
							type="warning"
							:closable="false"
						/>
					</el-form-item>
				</el-tab-pane>
				<el-tab-pane label="高级设置" name="2" lazy>
					<el-form-item label="指定抽奖次数">
						<div>
							<el-row :gutter="10">
								<el-col :span="10">
									<el-alert
										class="search-alert"
										show-icon
										title="手机号请输入完成后搜索"
										type="info"
										:closable="false"
									/>
								</el-col>
								<el-col :span="14" style="text-align: right">
									<el-input
										v-model="numKey"
										placeholder="请输入手机号或昵称"
										style="width: 200px"
									></el-input
									><el-button
										icon="el-icon-search"
										type="primary"
										@click="searchNum"
									/>
								</el-col>
							</el-row>

							<sc-form-table
								style="margin-top: 10px"
								v-model="prizesNum"
								:addTemplate="numberTemp"
								:isAdd="false"
							>
								<el-table-column
									prop="wxName"
									label="微信昵称"
									width="150"
								>
									<template #default="scope">
										{{ scope.row.wxName }}
									</template>
								</el-table-column>
								<el-table-column
									prop="mobile"
									label="手机号码"
									width="120"
								>
									<template #default="scope">
										{{ scope.row.mobile }}
									</template>
								</el-table-column>
								<el-table-column
									prop="number"
									label="设置抽奖次数"
									width="280"
								>
									<template #default="scope">
										<el-input
											v-model="scope.row.number"
											placeholder="请输入次数"
										></el-input>
									</template>
								</el-table-column>
							</sc-form-table>
							<el-alert
								class="cur-alert"
								show-icon
								title="注：每次保存后，都会对抽奖次数进行累加"
								type="warning"
								:closable="false"
							/>
							<div class="p-footer">
								<el-button
									@click="close"
									v-show="tabs.value == 2"
									>取 消</el-button
								>
								<el-button
									:loading="isSaveing"
									type="primary"
									v-show="tabs.value == 2"
									@click="saveNumber"
								>
									保存抽奖次数设置
								</el-button>
							</div>
						</div>
					</el-form-item>
				</el-tab-pane>
			</el-tabs>
		</el-form>

		<template #footer>
			<el-button @click="close" v-show="tabs.value != 2">取 消</el-button>
			<el-button
				:loading="isSaveing"
				type="primary"
				v-show="tabs.value != 2"
				@click="save"
			>
				保存奖品设置
			</el-button>
		</template>
		<internal ref="internal" />
	</sc-dialog>
</template>
<script>
import { defineAsyncComponent } from "vue";
const scEditor = defineAsyncComponent(() => import("@/components/scEditor"));
export default {
	components: {
		scEditor,
		internal: defineAsyncComponent(() => import("./internal")),
	},
	emits: ["complete"],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: "新增",
				edit: "编辑",
			},
			addTemplate: {
				id: "0",
				name: "",
				ratio: 0,
				code: "",
				users: [],
			},
			numberTemp: {
				id: "0",
				wxName: "",
				mobile: "",
				number: 0,
			},
			tabs: {
				value: 0,
			},
			isSaveing: false,
			visible: false,
			numKey: undefined,
			prizesNum: [],
			formData: {
				id: 0,
				name: undefined,
				subName: undefined,
				startTime: undefined,
				endTime: undefined,
				summary: undefined,
				pickCount: 0,
				prizes: [],
				status: true,
			},
			rules: {
				name: [
					{
						required: true,
						message: "请输入活动名称",
						trigger: "blur",
					},
				],
				prizes: [],
			},
		};
	},
	mounted() {},
	methods: {
		async open(row) {
			if (!row) {
				this.mode = "add";
			} else {
				this.mode = "edit";
				var res = await this.$API.carsprize.model.get(row.id);
				this.formData = res.data;
			}
			this.visible = true;
		},
		save() {
			this.$refs.formRef.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					let res = null;
					if (this.formData.id === 0) {
						res = await this.$API.carsprize.add.post(this.formData);
						this.formData.id = res.data;
					} else {
						res = await this.$API.carsprize.update.put(
							this.formData
						);
					}
					this.isSaveing = false;
					if (res.code == 200) {
						this.$emit("complete");
						this.$message.success(
							"活动保存成功，可以进一步操作高级设置"
						);
					} else {
						this.$alert(res.message, "提示", { type: "error" });
					}
				}
			});
		},
		async searchNum() {
			if (!this.numKey) {
				this.$message.warning("请输入手机号或昵称查询");
				return;
			}
			const res = await this.$API.member.page.get({ key: this.numKey });
			if (res.data.items.length == 0) {
				this.$message.warning("没有查询到相关的会员信息");
				return;
			}
			res.data.items.forEach((m) => {
				if (!this.arrExist(this.prizesNum, m)) {
					this.prizesNum.push({
						id: m.id,
						wxName: m.wxName,
						mobile: m.mobile,
						number: 0,
					});
				}
			});
		},
		saveNumber() {
			if (this.formData.id == 0) {
				this.$message.warning("请先保存奖品信息后，在设置抽奖次数");
				return;
			}
			if (this.prizesNum.length == 0) {
				this.$message.warning("请设置用户抽奖次数");
				return;
			}
			const param = {
				id: this.formData.id,
				users: this.prizesNum,
			};
			this.$confirm(
				`确定要保存为用户增加抽奖次数吗，每次保存都将增加次数？`,
				"提示",
				{
					type: "warning",
					confirmButtonText: "确定",
					cancelButtonText: "取消",
				}
			)
				.then(async () => {
					const loading = this.$loading();
					var res = await this.$API.carsprize.addDraw.post(param);
					if (res.code == 200) {
						loading.close();
						this.$message.success("保存成功");
					} else {
						this.$alert(res.message, "提示", { type: "error" });
					}
				})
				.catch(() => {});
		},
		beforeLeave(activeName) {
			if (this.formData.id == 0 && activeName == 2) {
				this.$message.warning("需要保存奖品后，在进行高级设置");
				return false;
			}
			return true;
		},
		tabsClick(e) {
			this.tabs.value = e.index;
		},
		arrExist(arr, m) {
			var result = arr.findIndex((item) => {
				return item.id == m.id;
			});
			return result == -1 ? false : true;
		},
		selectUser(m) {
			this.$prompt(``, "指定号码", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				inputErrorMessage: "输入不能为空",
				inputValidator: (value) => {
					if (value.trim().length < 1) {
						return "输入不能为空";
					}
				},
				beforeClose: (action, instance, done) => {
					if (action === "confirm") {
						let value = instance.inputValue;
						this.selectByMobile(value, done, m);
					} else {
						done();
					}
				},
			}).catch(() => {});
		},
		arrUserExist(arr, m) {
			var result = arr.findIndex((item) => {
				return item == m;
			});
			return result == -1 ? false : true;
		},
		async selectByMobile(v, done, m) {
			let that = this;
			const loading = this.$loading();
			var res = await this.$API.member.bymobile.get({ mobile: v });
			if (res.code == 200) {
				loading.close();
				if (!res.data) {
					this.$message.warning("没有查询到用户");
				} else {
					this.$message.success(
						"已将：【" + res.data.nickName + "】增加到内定人员~"
					);
					this.formData.prizes.forEach((it) => {
						if (it.name == m.name && it.code == m.code) {
							if (!that.arrUserExist(it.users, res.data.id)) {
								it.users.push(res.data.id);
							}
						}
					});
					done();
				}
			} else {
				this.$alert(res.message, "提示", { type: "error" });
			}
		},
		lookUser(m) {
			if (m.users.length == 0) {
				this.$message.warning("奖品没有设置内定人员~");
				return;
			}
			this.$refs.internal.open(m, this.formData.id);
		},
		close() {
			this.formData = {
				id: 0,
				name: undefined,
				subName: undefined,
				pickCount: 0,
				startTime: undefined,
				endTime: undefined,
				summary: undefined,
				prizes: [],
				status: true,
			};
			this.prizesNum = [];
			this.numKey = "";
			this.$refs.formRef.resetFields();
			this.visible = false;
			this.$emit("complete");
		},
	},
};
</script>
<style>
.column-dialog .el-dialog__body {
	padding-top: 0px;
	padding-bottom: 0px;
}
.p-footer {
	text-align: center;
	padding: 10px 0;
}
.tabs-pages {
	display: flex;
	flex-flow: column;
	flex-shrink: 0;
	height: 100%;
}
.tabs-pages > .el-tabs__header {
	background: #fff;
	margin: 0;
}
.tabs-pages > .el-tabs__header .el-tabs__nav-wrap {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
}
.tabs-pages > .el-tabs__header .el-tabs__item {
	height: 60px;
	line-height: 60px;
	font-size: 14px;
}
.tabs-pages > .el-tabs__content {
	overflow-x: hidden;
	overflow: auto;
}
[data-theme="dark"] .tabs-pages > .el-tabs__header {
	background: #2b2b2b;
}
.text-center {
	text-align: center;
}
.edior .el-form-item__content {
	display: block !important;
}
.ratio .el-input-group__append {
	padding: 0 10px !important;
}
.cur-alert {
	line-height: normal;
	margin-top: 10px;
	width: 96%;
}
.search-alert {
	line-height: normal;
	width: 96%;
}
</style>
